extern crate time;
use std::io::net::tcp::TcpStream;
use std::io::net::ip::SocketAddr;
//se time::Timespec;
  
//for i in {1..1000000}; do curl 127.0.0.1:8080/../; done;

struct Info {
    success:int,
    request: ~str,
    time_in_sec: f32,
    requests_per_sec:f32
}

fn main() {

	let args : ~[~str] = ::std::os::args();
	
	/*match args
	{
		Ok(()) => println!("{:s}",args[1]),
		Err(_) => println!("Something about the args")
	}*/

  	let ptime = time::precise_time_ns();
  	let req : ~str;

  	match args[2]
  	{
  		Ok() => req = x, 
  		Err(e) => println!("ERROR:{:s}",e)
  	}

  	//let req = args[2].clone();

	let mut run=0;

	match from_str::<int>(args[1]) 
	{
		Some(x) => run = x.clone(),
		None => println!("arg 1 must be the number of requets you want to make")
	}
	let ad = ~"127.0.0.1:8080";
	//let info1 = test_loop(run,ad,req.clone());
	let info = test_loop(run,ad,req.clone());

	println!("Made {:d} \"{:s}\"... requests",info.success,info.request);
	println!("it took about {:.2f} seconds to run \nwhich is about {:.2f} requests a second",info.time_in_sec,info.requests_per_sec);

	let p2time = time::precise_time_ns();

	let dif = (p2time-ptime) as f32;
	let dif2 = dif/1000000000.0;


	println!("TOTAL RUNNING TIME: {:f},",dif2 );
}

/*
A loop to test 

*/
fn test_loop(requests: int,ip: &str, request: ~str ) ->Info
{

	let mut get =0;
	let addr = from_str::<SocketAddr>(ip).unwrap();

	let t1 = time::precise_time_ns();
	
	for _ in range(0,requests)
	{
		let mut socket=TcpStream::connect(addr).unwrap();
		match socket.write(request.as_bytes())
		{
			Ok(_) =>  match socket.read_to_end() 
			{
	   			Ok(_) => 
	   			{ 			
	   						get+=1;
	   						//println!("S:{:.1s} Req {:d}", response, n)
	   			},
	   			Err(e)  => println!("ERROR: {:?}", e)
			},
			
			Err(e) => println!("ERROR: {:?}",e)
		}
		drop(socket);
	}

	let t2 = time::precise_time_ns();

	let dif = (t2-t1) as f32;
	let dif2 = dif/1000000000.0;

	let info : Info = Info 
	{
		success: get, 
		request: format!("{:.10s}",request), 
		time_in_sec: dif2,//time_dif_sec,
		requests_per_sec: (requests as f32)/dif2
	};

	return info;
}
	
 




